/**
 * @(#)com.framework.web.sys.service.UserService
 *
 * Copyright (c) 2014-2018 上海天跃科技有限公司
 *
 * DESC:
 *
 */
package com.framework.web.sys.service;

import com.framework.core.constant.Globals;
import com.framework.core.util.MyBeanUtils;
import com.framework.core.util.StringUtil;
import com.framework.web.sys.domain.Role;
import com.framework.web.sys.domain.RoleResource;
import com.framework.web.sys.domain.UserRole;
import com.framework.web.sys.repository.RoleRepository;
import com.framework.web.sys.repository.RoleResourceRepository;
import com.framework.web.sys.repository.UserRoleRepository;
import com.framework.web.sys.vo.RoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author fusf
 * @version 1.0  2016/1/8
 */
@Service
public class UserRoleService {


    @Autowired
    private UserRoleRepository userRoleRepository;

    @Autowired
    private RoleRepository roleRepository;

    /**
     * 根据用户id获取角色信息
     *
     * @param userId
     * @return
     */
    @Transactional
    public List<RoleVo> findCheckRoleByUserId(String userId) throws Exception{

        List<Role> roleList = roleRepository.findByStatusOrderBySortIndex(Globals.STATUS_YES);
        List<UserRole> userRoleList = userRoleRepository.findByUserId(userId);
        List<RoleVo> roleVoList = new ArrayList<RoleVo>();
        for(Role role : roleList) {
            RoleVo roleVo = new RoleVo();
            MyBeanUtils.copyBeanNotNull2Bean(role, roleVo);
            for(UserRole userRole : userRoleList) {
                if(role.getId().equals(userRole.getRoleId())) {
                    roleVo.setChecked("checked");
                    break;
                }
            }
            roleVoList.add(roleVo);
        }
        return roleVoList;
    }

    /**
     * 人员分配角色
     * @param id
     * @param roleId
     */
    @javax.transaction.Transactional
    public void saveUserRole(String id,String roleId) {
        //根据人员删除关联关系
        List<UserRole> userRoleList = userRoleRepository.findByUserId(id);
        userRoleRepository.delete(userRoleList);
        String[] array = roleId.split(",");
        for (String selectRoleId : array) {
            UserRole userRole = new UserRole();
            userRole.setUserId(id);
            userRole.setRoleId(selectRoleId);
            userRoleRepository.save(userRole);
        }
    }
}
